using B.S.XZYData.Api.Read.Application.Command.Process;
using B.S.XZYData.Domain.RBAC;
using B.S.XZYData.Domain.ZSH;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;
using Microsoft.Extensions.Logging;
using SqlSugar;

namespace B.S.XZYData.Api.Read.Application.Handler.Process
{
    /// <summary>
    /// 获取所有工序处理器
    /// </summary>
    public class GetAllProcessesHandler : IRequestHandler<GetAllProcessesCommand, ApiResult<List<ProcessDetailDto>>>
    {
        private readonly IBaseRepository<Domain.ZSHH.Process> _processRepo;
        private readonly IBaseRepository<RoleModel> _roleRepo;
        private readonly IBaseRepository<Defective> _defectiveRepo;
        private readonly ILogger<GetAllProcessesHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        public GetAllProcessesHandler(
            IBaseRepository<Domain.ZSHH.Process> processRepo,
            IBaseRepository<RoleModel> roleRepo,
            IBaseRepository<Defective> defectiveRepo,
            ILogger<GetAllProcessesHandler> logger)
        {
            _processRepo = processRepo;
            _roleRepo = roleRepo;
            _defectiveRepo = defectiveRepo;
            _logger = logger;
        }

        /// <summary>
        /// 处理获取所有工序命令
        /// </summary>
        public async Task<ApiResult<List<ProcessDetailDto>>> Handle(GetAllProcessesCommand request, CancellationToken cancellationToken)
        {
            var res = new ApiResult<List<ProcessDetailDto>>();
            try
            {
                // 查询所有工序
                var processList = await _processRepo.GetAll()
                    .Where(x => !x.IsDeleted)
                    .ToListAsync();
                
                // 在内存中进行多字段排序
                processList = processList
                    .OrderBy(x => x.RoutdId)  // 先按工艺ID排序
                    .ThenBy(x => x.ProcessNumber)  // 再按工序编号排序
                    .ToList();

                // 转换为DTO并处理数据转换
                var processDtoList = await ConvertToDtoList(processList);

                res.Data = processDtoList;
                res.Code = ApiEnum.Success;
                res.Msg = "获取所有工序成功";
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取所有工序异常");
                res.Code = ApiEnum.Error;
                res.Msg = "获取所有工序异常：" + ex.Message;
            }

            return res;
        }

        /// <summary>
        /// 转换为DTO列表并处理数据转换
        /// </summary>
        private async Task<List<ProcessDetailDto>> ConvertToDtoList(List<Domain.ZSHH.Process> processList)
        {
            var result = new List<ProcessDetailDto>();

            foreach (var process in processList)
            {
                var dto = new ProcessDetailDto
                {
                    Id = process.Id,
                    ProcessNumber = process.ProcessNumber,
                    RoutdId = process.RoutdId,
                    ProcessName = process.ProcessName,
                    ReportingPermissions = await ConvertReportingPermissionsToNames(process.ReportingPermissions),
                    ReportingRatio = process.ReportingRatio ?? 1,
                    DefectiveItemList = await ConvertDefectiveItemListToNames(process.DefectiveItemList),
                    TestField1 = process.TestField1,
                    TestField2 = process.TestField2,
                    CreatorDate = process.CreatorDate,
                    Creator = process.Creator,
                    UpdatorDate = process.UpdatorDate,
                    Updator = process.Updator
                };

                result.Add(dto);
            }

            return result;
        }

        /// <summary>
        /// 将报工权限ID转换为角色名称
        /// </summary>
        private Task<string> ConvertReportingPermissionsToNames(string? reportingPermissions)
        {
            if (string.IsNullOrEmpty(reportingPermissions))
                return Task.FromResult(string.Empty);

            var permissionIds = reportingPermissions.Split(',', StringSplitOptions.RemoveEmptyEntries);
            var roleNames = new List<string>();

            foreach (var permissionId in permissionIds)
            {
                if (int.TryParse(permissionId.Trim(), out var roleId))
                {
                    if (roleId == 0)
                    {
                        roleNames.Add("所有人");
                    }
                    else
                    {
                        var role = _roleRepo.GetAll()
                            .Where(x => !x.IsDeleted && x.Id == roleId)
                            .ToList()
                            .FirstOrDefault();
                        
                        if (role != null)
                        {
                            roleNames.Add(role.RoleName);
                        }
                        else
                        {
                            roleNames.Add($"角色ID:{roleId}");
                        }
                    }
                }
                else
                {
                    // 如果不是数字，可能是角色名称
                    roleNames.Add(permissionId.Trim());
                }
            }

            return Task.FromResult(string.Join(",", roleNames));
        }

        /// <summary>
        /// 将不良品项ID转换为名称描述
        /// </summary>
        private Task<string> ConvertDefectiveItemListToNames(string? defectiveItemList)
        {
            if (string.IsNullOrEmpty(defectiveItemList))
                return Task.FromResult(string.Empty);

            var items = defectiveItemList.Split(',', StringSplitOptions.RemoveEmptyEntries);
            var descriptions = new List<string>();

            foreach (var item in items)
            {
                var itemId = item.Trim();
                
                // 尝试解析为数字ID
                if (int.TryParse(itemId, out var defectiveId))
                {
                    var defective = _defectiveRepo.GetAll()
                        .Where(x => !x.IsDeleted && x.Id == defectiveId)
                        .ToList()
                        .FirstOrDefault();

                    if (defective != null)
                    {
                        descriptions.Add($"{defective.DefectiveCode} | {defective.DefectiveName}");
                    }
                    else
                    {
                        descriptions.Add(itemId);
                    }
                }
                else
                {
                    // 如果不是数字ID，尝试按原来的逻辑处理
                    var parts = itemId.Split('|', StringSplitOptions.RemoveEmptyEntries);
                    if (parts.Length >= 2)
                    {
                        var code = parts[0].Trim();
                        var description = parts[1].Trim();

                        var defective = _defectiveRepo.GetAll()
                            .Where(x => !x.IsDeleted && x.DefectiveCode == code)
                            .ToList()
                            .FirstOrDefault();

                        if (defective != null)
                        {
                            descriptions.Add($"{defective.DefectiveCode} | {defective.DefectiveName}");
                        }
                        else
                        {
                            descriptions.Add(itemId);
                        }
                    }
                    else
                    {
                        descriptions.Add(itemId);
                    }
                }
            }

            return Task.FromResult(string.Join(",", descriptions));
        }
    }
}
